package com.duan.nowcoder.community.service;

import com.duan.nowcoder.community.util.RedisKeyUtil;
import com.duan.nowcoder.community.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
public class LikeServiceImpl implements LikeService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void like(int userId, int entityType, int entityId, int entityUserId) {
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
                String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);
                boolean isMember = redisUtil.sHasKey(entityLikeKey, userId);
                operations.multi();
                if (isMember) {
                    operations.opsForSet().remove(entityLikeKey, userId);
                    operations.opsForSet().remove(userLikeKey, userId);
                } else {
                    operations.opsForSet().add(entityLikeKey, userId);
                    operations.opsForSet().add(userLikeKey, userId);
                }
                return operations.exec();
            }
        });
    }

    @Override
    public Long findEntityLikeCount(int entityType, int entityId) {
        String EntityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisUtil.sSize(EntityLikeKey);
    }

    @Override
    public int isEntityLike(int userId, int entityType, int entityId) {
        String EntityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisUtil.sHasKey(EntityLikeKey, userId) ? 1 : 0;
    }

    @Override
    public Long findUserLike(int entityUserId) {
        String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);
        Long count = redisUtil.sSize(userLikeKey);
        return count == null ? 0 : count;
    }

    @Override
    public void deleteEntityLike(int entityId, int entityType) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        redisUtil.del(entityLikeKey);
    }
}
